package com.example.cardgame

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.gridlayout.widget.GridLayout
import androidx.activity.ComponentActivity
import androidx.activity.enableEdgeToEdge
import cn.edu.sicnu.cardgame.CardMatchingGame

class MainActivity : ComponentActivity(),View.OnClickListener {

    private lateinit var game:CardMatchingGame
    private val cardButtons = mutableListOf<Button>()
    private var highScore: Int = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)

        val gridLayout = findViewById<GridLayout>(R.id.gridLayout)

        if (gridLayout != null) {
            for (i in 0 until gridLayout.childCount) {
                val child = gridLayout.getChildAt(i)
                if (child is Button) {
                    child.setOnClickListener(this)
                    cardButtons.add(child)
                }
            }
        }
        game = CardMatchingGame(cardButtons.count())
        updateUI()

        val reset = findViewById<Button>(R.id.button3)
        reset.setOnClickListener{
            game = CardMatchingGame(cardButtons.count())
            updateUI()
        }

        // 更新最高分
        if (game.score > highScore) {
            highScore = game.score
        }

        // 返回按钮
        val button2 = findViewById<Button>(R.id.button39)
        button2.setOnClickListener {

            val intent = Intent(this, MainActivity1::class.java).apply {
                putExtra("HIGH_SCORE", highScore) // 通过Intent传递最高分
            }
            startActivity(intent)
        }

    }
    @SuppressLint("DefaultLocale")
    private fun updateUI(){
        for(button in cardButtons){
            val index = cardButtons.indexOf(button)
            val card = game.cardAtIndex(index)
            button.isEnabled = !card.isMatched
            if(card.isChosen){
                button.text = card.toString()
                button.setBackgroundColor(Color.WHITE)
            }
            else{
                button.text = ""
                button.setBackgroundResource(R.drawable.img)
            }
        }
        val score = findViewById<TextView>(R.id.textView6)
        score.text = String.format("%s%d",getString(R.string.score1),game.score)
        // 检查并更新最高分
        if (game.score > highScore) {
            highScore = game.score
        }
    }
    override fun onClick(v:View?){
        if(v is Button){
            val index = cardButtons.indexOf(v)
            game.chooseCardAtIndex(index)
            updateUI()
        }
    }

}
